import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, message, Space, Tabs, Tag, Typography } from 'antd'
import { EditFormInline } from '@/components/CustomForm'
import { FormInstance, useForm } from 'antd/es/form/Form'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './FormShare.less'
import { useFormBase } from '../useForm'
import { getPurchaseOrderDetail, updatePurchaseInfo } from '@/api/purchase'
import {
  CONTRACT_STATUS_TEXT,
  ORDER_STATUS_TEXT,
  PURCHASEWAY_TEXT,
  QC_STATUS_TEXT,
  RESERVE_INVOICE_STATUS_TEXT,
} from '@/constant/purchase'
import useSearchWarehouse from '@/hooks/useSearchWarehouse'
import useSearchUser from '@/hooks/useSearchUser'
import { useAppSelector } from '@/store/hooks'
import dayjs from 'dayjs'
import Detailed from './Detailed'
import Schedule from './Schedule'
import Arrival from './Arrival'
import { applicationTypeEnum, OperationLogType } from '@/constant'
import LogsDrawer from '@/components/LogsDrawer'
import useViewLogs from '@/hooks/useViewLogs'
import PermissionButton from '@/components/PermissionButton'
const Index: React.FC = () => {
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [FormStyleBase] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [baseInfo, setbaseInfo] = useState<IDesListType>([
    { label: '采购方式', key: 'purchaseType', content: '-', format: (rows) => PURCHASEWAY_TEXT[rows.purchaseType] },
    { label: '商品季节', key: 'productSeason', content: '-' },
    { label: '季节分组', key: 'seasonGroup', content: '-' },
    { label: '年份', key: 'year', content: '-' },
    { label: '大类', key: 'firstClassName', content: '-' },
    { label: '供应商', key: 'supplierName', content: '-' },
    { label: '仓库', key: 'warehouseName', content: '-' },
    { label: '入库时是否冻结', key: 'freeze', content: '-', format: (rows) => (rows.freeze === 1 ? '是' : '否') },
    { label: '批次', key: 'batchNum', content: '-', format: (rows) => (rows.batchNum > 0 ? rows.batchNum : '-') },
    { label: '企划意向交期', key: 'planDate', content: '-', hidden: !isRoot },
    { label: '要求到货日期', key: 'requiredArrivalTime', content: '-', hidden: !isRoot },
    { label: '跟单办事处', key: 'trackOffice', content: '-' },
    { label: '供应链跟单', key: 'trackOrderPerson', content: '-' },
    { label: '供应链回复发货日期', key: 'replyDeliveryTime', content: '-', hidden: !isRoot },
    { label: '订单季节', key: 'seasonName', content: '-' },
    { label: '内部留言', key: 'internalRemark', content: '-', hidden: !isRoot },
  ])
  const [isEdit, setisEdit] = useState<boolean>(false)
  const [relatedOrders, setrelatedOrders] = useState<IDesListType>([
    {
      label: '订单合同',
      key: 'orgName',
      content: '-',
      format: (rows) => {
        return rows.contractCode ? (
          <Typography.Paragraph>
            <Typography.Link onClick={() => navigate('/purchase/contract/list?contractCode=' + rows.contractCode)}>
              {rows.contractCode}
            </Typography.Link>
            <Typography.Text>
              {rows.contractStatus != null && rows.contractStatus >= 0
                ? '（' + CONTRACT_STATUS_TEXT[rows.contractStatus] + '）'
                : ''}
            </Typography.Text>
          </Typography.Paragraph>
        ) : (
          '-'
        )
      },
    },
    {
      label: 'QC单',
      key: 'qualityOrderVOList',
      content: '-',
      format: (rows) => {
        return rows.qualityOrderVOList && rows.qualityOrderVOList.length > 0
          ? rows?.qualityOrderVOList?.map((item: any, index: number) => {
              return (
                <div key={item.qualityOrderCode} style={{ display: 'flex', flexWrap: 'wrap' }}>
                  <Typography.Paragraph>
                    {index === 0 ? '' : '，'}
                    <Typography.Link
                      onClick={() => navigate('/purchase/qc/list?qualityOrderCode=' + item.qualityOrderCode)}
                    >
                      {item.qualityOrderCode}
                    </Typography.Link>
                    <Typography.Text>
                      {item?.qualityStatus
                        ? '（' + item?.qualityPhaseName + '：' + QC_STATUS_TEXT[item?.qualityStatus] + '）'
                        : ''}
                    </Typography.Text>
                  </Typography.Paragraph>
                </div>
              )
            })
          : '-'
      },
    },
    {
      label: '预约发货单',
      key: 'reserveInvoiceList',
      content: '-',
      format: (rows) => {
        return rows.reserveInvoiceList && rows.reserveInvoiceList.length > 0
          ? rows?.reserveInvoiceList?.map((item: any, index: number) => {
              return (
                <Typography.Paragraph key={item.reserveInvoiceCode}>
                  {index === 0 ? '' : '，'}
                  <Typography.Link
                    onClick={() => navigate('/purchase/delivery/list?reserveInvoiceCode=' + item.reserveInvoiceCode)}
                  >
                    {item.reserveInvoiceCode}
                  </Typography.Link>
                  <Typography.Text>
                    {item.reserveInvoiceStatus >= 0
                      ? '（' + RESERVE_INVOICE_STATUS_TEXT[item.reserveInvoiceStatus] + '）'
                      : ''}
                  </Typography.Text>
                </Typography.Paragraph>
              )
            })
          : '-'
      },
    },
  ])
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'purchaseOrderCode',
    OperationLogType.PURCHASEORDER,
  )
  const [query] = useSearchParams()
  const navigate = useNavigate()
  const id = query.get('id')
  const { WareHouseOptions, handleSearchWareHouse, setWareHouseOptions } = useSearchWarehouse()
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [tagItems, settagItems] = useState<any[]>([])
  useEffect(() => {
    getDetail()
  }, [])
  const getDetail = async () => {
    const res = await getPurchaseOrderDetail(id)
    if (res.code === 200) {
      const details = res.data
      setDetail(details)
      details?.purchaseOrderCode && (document.title = details.purchaseOrderCode)
      handleDetailFactory(baseInfo, details, setbaseInfo)
      handleDetailFactory(relatedOrders, details, setrelatedOrders)
      if (details.status == 2 || details.status == 3 || details.status == 5) {
        settagItems([
          {
            label: `生产进度跟踪`,
            key: 'schedule',
            children: <Schedule detailInfo={details} />,
          },
          {
            label: `到货批次`,
            key: 'arrival',
            children: <Arrival detailInfo={details} getDetail={getDetail} />,
          },
        ])
      }
    }
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList
      ?.filter((item) => !item?.hidden)
      ?.map((item) => {
        if (typeof item.format === 'function') {
          return {
            ...item,
            content: item.format(targetInfo),
          }
        } else {
          return {
            ...item,
            content: targetInfo[item.key + ''] || '-',
          }
        }
      })
    set(res)
  }
  const startEdit = (Form: FormInstance, isEdit: boolean, setisEdit: React.Dispatch<React.SetStateAction<boolean>>) => {
    if (isEdit) {
      Form.validateFields().then(async (data) => {
        setispedding(true)
        const params = {
          ...data,
          id,
          requiredArrivalTime: data.requiredArrivalTime && dayjs(data.requiredArrivalTime).format('YYYY-MM-DD'),
          freeze: data.freeze ? 1 : 0,
          trackOrderPersonWorkId: data.trackOrderPersonWorkId.value,
          trackOrderPerson: data.trackOrderPersonWorkId?.label?.split('-')[1],
          batchNum: data.batchNum ? data.batchNum : 0,
          replyDeliveryTime: data.replyDeliveryTime ? dayjs(data.replyDeliveryTime).format('YYYY-MM-DD') : null,
        }
        const res = await updatePurchaseInfo(params).finally(() => setispedding(false))
        if (res.code === 200) {
          message.success('操作成功')
          setisEdit(false)
          getDetail()
        }
      })
    } else {
      setisEdit(true)
      Form.setFieldsValue({
        requiredArrivalTime: detailInfo.requiredArrivalTime ? dayjs(detailInfo.requiredArrivalTime) : null,
        replyDeliveryTime: detailInfo.replyDeliveryTime ? dayjs(detailInfo.replyDeliveryTime) : null,
        warehouse: detailInfo.warehouse,
        freeze: !!detailInfo.freeze,
        trackOrderPersonWorkId: {
          label: detailInfo.trackOrderPersonWorkId + '-' + detailInfo.trackOrderPerson,
          value: detailInfo.trackOrderPersonWorkId,
        },
        seasonCode: detailInfo.seasonCode,
        batchNum: detailInfo.batchNum >= 0 ? detailInfo.batchNum : 0,
        trackOffice: detailInfo.trackOffice || null,
      })
      setWareHouseOptions([{ label: detailInfo.warehouseName, value: detailInfo.warehouse }])
      setUserOptions([
        {
          label: detailInfo.trackOrderPersonWorkId + '-' + detailInfo.trackOrderPerson,
          value: detailInfo.trackOrderPersonWorkId,
        },
      ])
    }
  }
  return (
    <DetailContainer
      className="purchase_order_add_page"
      footer={
        <Space>
          {isRoot && id && Object.keys(detailInfo).length > 0 && (
            <Button type="primary" ghost onClick={() => viewLogs(detailInfo)}>
              查看日志
            </Button>
          )}
        </Space>
      }
    >
      {id && (
        <Descriptions title="">
          <div className="poap_header_detail_box">
            <span>采购订单号：</span>
            <span className="order_no">{detailInfo?.purchaseOrderCode || '-'}</span>
            {detailInfo?.status === 0 ? (
              <Tag color="cyan">待提交</Tag>
            ) : detailInfo?.status === 1 ? (
              <Tag color="blue">待审核</Tag>
            ) : detailInfo?.status === 2 ? (
              <Tag color="geekblue">生产中</Tag>
            ) : detailInfo?.status === 3 ? (
              <Tag color="green">已完成-全部收货</Tag>
            ) : detailInfo?.status === 4 ? (
              <Tag color="volcano">已取消</Tag>
            ) : detailInfo?.status === 5 ? (
              <Tag color="orange">已完成-部分收货</Tag>
            ) : null}
            {detailInfo?.deliveryStatus === 0 ? (
              <Tag color="magenta">全部到货</Tag>
            ) : detailInfo?.deliveryStatus === 1 ? (
              <Tag color="lime">部分到货</Tag>
            ) : null}
            {detailInfo?.orderType === 0 ? (
              <Tag color="purple">首单</Tag>
            ) : detailInfo?.orderType === 1 ? (
              <Tag color="gold">返单</Tag>
            ) : null}
          </div>
        </Descriptions>
      )}
      <Descriptions
        title="基础信息"
        list={isEdit ? [] : baseInfo}
        extra={
          isRoot ? (
            <Space>
              {detailInfo?.status == 0 ? (
                <PermissionButton
                  permission="editPurchaseBase"
                  type="primary"
                  onClick={() => startEdit(FormStyleBase, isEdit, setisEdit)}
                  loading={ispedding}
                >
                  {isEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              ) : null}
              {isEdit ? (
                <Button
                  onClick={() => {
                    setisEdit(false)
                    getDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          ) : null
        }
      >
        <EditFormInline
          className="sep_forminline_style"
          editConfig={useFormBase({
            detailInfo,
            WareHouseOptions,
            handleSearchWareHouse,
            UserOptions,
            handleSearchUser,
            DICTDATA,
            isRoot,
          })}
          form={FormStyleBase}
        />
      </Descriptions>
      <Descriptions
        title="关联订单"
        list={relatedOrders}
        column={{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }}
      ></Descriptions>
      <div className="tabs_wrap_layout">
        {Object.keys(detailInfo).length > 0 && (
          <Tabs
            defaultActiveKey="detailed"
            items={[
              {
                label: `商品明细`,
                key: 'detailed',
                children: <Detailed detailInfo={detailInfo} getDetail={getDetail} />,
              },
            ].concat(tagItems)}
          />
        )}
      </div>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
    </DetailContainer>
  )
}
export default Index
